package com.cb.web.wasf.tag;

import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.DynamicAttributes;
import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.tagext.TryCatchFinally;

/**
 * @author CBO
 */
public class UseTemplateTag extends TagSupport implements TryCatchFinally, DynamicAttributes {

    private static final String FRAGMENT_BY_NAME_RAN = UseTemplateTag.class.getName() + "-FRAGMENT_BY_NAME_RAN";
    private String name;
    private Map<String, String> fragmentByName;

    public UseTemplateTag() {
        fragmentByName = new HashMap<String, String>();
    }

    @Override
    public void setDynamicAttribute(String uri, String localName, Object value) throws JspException {
        if (value != null) {
            putFragment(localName, value.toString());
        }
    }

    public void setName(String name) {
        this.name = name;
    }

    void putFragment(String name, String content) {
        fragmentByName.put(name, content);
    }

    @Override
    public int doStartTag() throws JspException {
        return EVAL_BODY_INCLUDE;
    }

    @Override
    public int doEndTag() throws JspException {
        try {
            pageContext.getRequest().setAttribute(FRAGMENT_BY_NAME_RAN, fragmentByName);
            pageContext.include(name);
            pageContext.setAttribute(FRAGMENT_BY_NAME_RAN, null);
        } catch (Exception ioe) {
            throw new JspException(ioe);
        }
        return EVAL_PAGE;
    }

    @Override
    public void doCatch(Throwable throwable) throws Throwable {
        throw throwable;
    }

    @Override
    public void doFinally() {
        this.name = null;
        this.fragmentByName.clear();
    }

    static Map<String, String> getFragmentByName(ServletRequest servletRequest) {
        return (Map<String, String>) servletRequest.getAttribute(FRAGMENT_BY_NAME_RAN);
    }

}